package org.example.server.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.example.common.properties.JwtProperties;
import org.example.common.utils.jwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Component
public class interCepter implements HandlerInterceptor {

   @Autowired
   private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/login")){
            //登录请求直接放行
            System.out.println("登录请求直接放行");

            return true;
        }
        String token = request.getHeader("token");
        if(token == null||token.isEmpty()){
            System.out.println("token为空");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401未授权
            return false;
        }
        try{
            jwtUtil.parseToken(token,jwtProperties.getAdminSecretKey());
        }catch (Exception e){
            System.out.println("token解析失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401未授权
            return false;

        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
